package com.kelvem.saas.workbanch.core.manager.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kelvem.saas.workbanch.core.base.BaseCriteria;
import com.kelvem.saas.workbanch.core.base.BaseService;
import com.kelvem.saas.workbanch.core.base.Page;
import com.kelvem.saas.workbanch.core.exception.SaasAssert;
import com.kelvem.saas.workbanch.core.exception.SaasException;
import com.kelvem.saas.workbanch.core.manager.dao.BizPageDomDao;
import com.kelvem.saas.workbanch.core.manager.model.BizPageDomEntity;
import com.kelvem.saas.workbanch.core.manager.model.MetaTableColumnEntity;
import com.kelvem.saas.workbanch.core.manager.request.BizPageDomQueryVo;
import com.kelvem.saas.workbanch.core.utils.DateUtil;
import com.kelvem.saas.workbanch.fsm.dao.BaseDao;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 实体业务参数Service
 *
 * @author kelvem
 * @version 1.0
 */
@Service
@Slf4j
public class BizPageDomService extends BaseService<BizPageDomEntity, BizPageDomQueryVo> {

    @Resource
    private BizPageDomDao bizPageDomDao;

    /**
     * 增加实体业务参数
     *
     * @param bizPageDom 实体业务参数信息
     * @return Long 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public Long addBizPageDom(BizPageDomEntity bizPageDom) {
        
        log.info("BizPageDomService:addBizPageDom:start, bizPageDom=【{}】", bizPageDom);
        SaasAssert.notNull(bizPageDom);
        
        try {
            if (bizPageDom.getCreateTime() == null) {
                bizPageDom.setCreateTime(DateUtil.now());
            }
            if (bizPageDom.getUpdateTime() == null) {
                bizPageDom.setUpdateTime(DateUtil.now());
            }
        
            bizPageDomDao.insert(bizPageDom);
            Long bizPageDomId = bizPageDom.getId();
            log.info("BizPageDomService:addBizPageDom:end, bizPageDomId={}", bizPageDomId);
        
            return bizPageDom.getId();
        } catch (Exception e) {
            String msg = String.format("BizPageDomService:addBizPageDom:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    /**
     * 修改实体业务参数
     *
     * @param bizPageDom 实体业务参数信息
     * @return 更新记录数
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateBizPageDom(BizPageDomEntity bizPageDom) {
        
        log.info("BizPageDomService:updateBizPageDom:start, bizPageDom=【{}】", bizPageDom);
        SaasAssert.notNull(bizPageDom);
        SaasAssert.notNull(bizPageDom.getId());

        try {
            int count = bizPageDomDao.updateById(bizPageDom);
            log.info("BizPageDomService:updateBizPageDom:end, count={}", count);
            return count;
        } catch (Exception e) {
            String msg = String.format("BizPageDomService:updateBizPageDom:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    /**
     * 删除实体业务参数
     *
     * @param bizPageDomId 实体业务参数id
     * @return 删除记录数
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizPageDom(Long bizPageDomId) {

        log.info("BizPageDomService:deleteBizPageDom:start, bizPageDomId={}", bizPageDomId);
        SaasAssert.notNull(bizPageDomId);
        
        try {
            int count = bizPageDomDao.deleteById(bizPageDomId);
            log.info("BizPageDomService:deleteBizPageDom:end, count={}", count);
            return count;
        } catch (Exception e) {
            String msg = String.format("BizPageDomService:deleteBizPageDom:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }
    
    /**
     * 查询实体业务参数分页数据
     *
     * @param bizPageDomQueryVo 查询用
     * @return Page<BizPageDomDto>
     */
    public Page<BizPageDomEntity> queryBizPageDomPage(BizPageDomQueryVo bizPageDomQueryVo) {
        
        log.info("BizPageDomService:queryBizPageDomPage:start, bizPageDomQueryVo=【{}】", bizPageDomQueryVo);
        SaasAssert.notNull(bizPageDomQueryVo);
        
        try {
            Page<BizPageDomEntity> page = super.queryPage(bizPageDomQueryVo);
            log.info("BizPageDomService:queryBizPageDomPage:end, page.size={}", page.getRecords().size());
            return page;
        } catch (Exception e) {
            String msg = String.format("BizPageDomService:queryBizPageDomPage:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    /**
     * 查询实体业务参数列表数据
     *
     * @param bizPageDomQueryVo 查询用
     * @return List<BizPageDom>
     */
    public List<BizPageDomEntity> queryBizPageDomList(BizPageDomQueryVo bizPageDomQueryVo) {
        
        log.info("BizPageDomService:queryBizPageDomList:start, bizPageDomQueryVo=【{}】", bizPageDomQueryVo);
        SaasAssert.notNull(bizPageDomQueryVo);
        
        try {
            List<BizPageDomEntity> list = super.queryList(bizPageDomQueryVo);
            log.info("BizPageDomService:queryBizPageDomList:end, list.size={}", list.size());
            return list;
        } catch (Exception e) {
            String msg = String.format("BizPageDomService:queryBizPageDomList:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    /**
     * 根据id查询实体业务参数信息
     *
     * @param bizPageDomId 实体业务参数id
     * @return BizPageDom
     */
    public BizPageDomEntity getBizPageDomById(Long bizPageDomId) {

        log.info("BizPageDomService:getBizPageDomById:start, bizPageDomId={}", bizPageDomId);
        SaasAssert.notNull(bizPageDomId);
        
        try {
            BizPageDomEntity bizPageDom = bizPageDomDao.selectById(bizPageDomId);
            log.info("BizPageDomService:getBizPageDomById:end, bizPageDomInfo=【{}】", bizPageDom);
            return bizPageDom;
        } catch (Exception e) {
            String msg = String.format("BizPageDomService:getBizPageDomById:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    /**
     * 构建查询用Criteria
     * 基类的queryPage, queryList方法使用
     *
     * @param queryVo 查询用
     * @return BaseCriteria
     */
    @Override
    public BaseCriteria<BizPageDomEntity> buildQueryCriteria(BizPageDomQueryVo queryVo) {
        BaseCriteria<BizPageDomEntity> criteria = new BaseCriteria<>();
        criteria.orderByDesc("id");

        // 主键
        Long id = queryVo.getId();
        if (super.isNotEmpty(id)) {
            criteria.andEqualTo("id", queryVo.getId());
        }
        
        // 创建时间
        Date startCreateTime = queryVo.getStartCreateTime();
        if(super.isNotEmpty(startCreateTime)) {
            criteria.andGreaterThanOrEqualTo("createTime", startCreateTime);
        }
        Date endCreateTime = queryVo.getEndCreateTime();
        if(super.isNotEmpty(endCreateTime)) {
            criteria.andLessThanOrEqualTo("createTime", endCreateTime);
        }

        // 实体业务id
        Long bizPageId = queryVo.getBizPageId();
        if (super.isNotEmpty(bizPageId)) {
            criteria.andEqualTo("bizPageId", bizPageId);
        }

        // 实体表id
        Long metaTableId = queryVo.getMetaTableId();
        if (super.isNotEmpty(metaTableId)) {
            criteria.andEqualTo("metaTableId", metaTableId);
        }

        // 控件类型, number:数字; varchar128:短文字; varchar1024:长文字; biz_id:主键; biz_state:状态
        String controlType = queryVo.getControlType();
        if (super.isNotEmpty(controlType)) {
            criteria.andEqualTo("controlType", controlType);
        }

        // 字段类型, int:数字; varchar:文字; datetime:时间; long:长数字
        String dbType = queryVo.getDbType();
        if (super.isNotEmpty(dbType)) {
            criteria.andEqualTo("dbType", dbType);
        }

        // 字段默认值
        String defaultValue = queryVo.getDefaultValue();
        if (super.isNotEmpty(defaultValue)) {
            criteria.andEqualTo("defaultValue", defaultValue);
        }

        // 必填, 1:必填; 0:选填
        Integer requireFlag = queryVo.getRequireFlag();
        if (super.isNotEmpty(requireFlag)) {
            criteria.andEqualTo("requireFlag", requireFlag);
        }

        // 可排序, 1:可排序; 0:不可排序
        Integer sortFlag = queryVo.getSortFlag();
        if (super.isNotEmpty(sortFlag)) {
            criteria.andEqualTo("sortFlag", sortFlag);
        }

        // 列展示, 1:展示; 0:不展示
        Integer showFlag = queryVo.getShowFlag();
        if (super.isNotEmpty(showFlag)) {
            criteria.andEqualTo("showFlag", showFlag);
        }

        // 创建人
        String createUid = queryVo.getCreateUid();
        if (super.isNotEmpty(createUid)) {
            criteria.andEqualTo("createUid", createUid);
        }

        // 更新人
        String updateUid = queryVo.getUpdateUid();
        if (super.isNotEmpty(updateUid)) {
            criteria.andEqualTo("updateUid", updateUid);
        }

        return criteria;
    }

    @Override
    public BaseDao<BizPageDomEntity> getDao() {
        return this.bizPageDomDao;
    }


    /**
     * 查询页面元素列表数据
     *
     * @param bizPageId 页面id
     * @return List<BizPageDom>
     */
    public List<BizPageDomEntity> queryBizPageDomList(Long bizPageId) {

        log.info("BizPageDomService:queryBizPageDomList:start, bizPageId=【{}】", bizPageId);
        SaasAssert.notNull(bizPageId);

        try {
            BizPageDomQueryVo bizPageDomQueryVo = BizPageDomQueryVo.builder().bizPageId(bizPageId).build();
            List<BizPageDomEntity> list = super.queryList(bizPageDomQueryVo);
            log.info("BizPageDomService:queryBizPageDomList:end, list.size={}", list.size());
            return list;
        } catch (Exception e) {
            String msg = String.format("BizPageDomService:queryBizPageDomList:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    /**
     * 通过实体业务id, 删除实体业务参数
     *
     * @param bizPageId 实体业务id
     * @return 删除记录数
     */
    @Transactional(rollbackFor = Exception.class)
    public int deleteByBizPageId(Long bizPageId) {

        log.info("BizPageDomService:deleteByBizPageId:start, bizPageId={}", bizPageId);
        SaasAssert.notNull(bizPageId);

        try {
            LambdaQueryWrapper<BizPageDomEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(BizPageDomEntity::getBizPageId, bizPageId);
            int count = bizPageDomDao.delete(lambdaQueryWrapper);
            log.info("BizPageDomService:deleteByBizPageId:end, count={}", count);
            return count;
        } catch (Exception e) {
            String msg = String.format("BizPageDomService:deleteByBizPageId:error, %s", e.getMessage());
            log.error(msg, e);
            throw new SaasException(msg);
        }
    }

    public BizPageDomEntity convert(MetaTableColumnEntity column, Map<String, String> panelInfo, Long bizPageId) {
        BizPageDomEntity param = new BizPageDomEntity();
        param.setChName(column.getChName());
        param.setControlType(column.getControlType());
        param.setDefaultValue(column.getDefaultValue());
        param.setEnName(column.getEnName());
        param.setOptionValue(column.getOptionValue());
        param.setPropertyJson("{}");
        param.setSpan(column.getSpan());
        param.setSpan(column.getWidth());
        param.setDbType(column.getDbType());
        param.setRequireFlag(column.getRequireFlag());
        param.setMetaTableColumnId(column.getId());
        param.setSortNo(column.getSortNo());
        param.setSortFlag(column.getSortFlag());
        param.setShowFlag(column.getShowFlag()); // todo
        param.setBizPageId(bizPageId);
        param.setPanelType(panelInfo.get("type"));
        param.setPanelUuid(panelInfo.get("uuid"));
        param.setMetaTableId(column.getMetaTableId());
        param.setSourceType(column.getSourceType());
        param.setMemo("");

        return param;
    }
}
